package com.seafood.controller;

import com.seafood.common.PageResult;
import com.seafood.common.Result;
import com.seafood.dto.ProductDTO;
import com.seafood.dto.ProductSearchDTO;
import com.seafood.service.ProductService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 产品控制器
 */
@Tag(name = "产品管理", description = "产品相关API")
@RestController
@RequestMapping("/products")
@RequiredArgsConstructor
@Validated
public class ProductController {
    
    private final ProductService productService;
    
    /**
     * 分页获取产品列表
     */
    @Operation(summary = "获取产品列表", description = "分页获取产品列表")
    @GetMapping
    public Result<PageResult<ProductDTO>> getProducts(
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "12") Integer size) {
        try {
            PageResult<ProductDTO> products = productService.getProducts(page, size);
            return Result.success(products);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据ID获取产品详情
     */
    @Operation(summary = "获取产品详情", description = "根据产品ID获取详细信息")
    @GetMapping("/{id}")
    public Result<ProductDTO> getProductById(@PathVariable Long id) {
        try {
            ProductDTO product = productService.getProductById(id);
            return Result.success(product);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据分类获取产品
     */
    @Operation(summary = "按分类获取产品", description = "根据分类ID分页获取产品")
    @GetMapping("/category/{categoryId}")
    public Result<PageResult<ProductDTO>> getProductsByCategory(
            @PathVariable Long categoryId,
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "12") Integer size) {
        try {
            PageResult<ProductDTO> products = productService.getProductsByCategory(categoryId, page, size);
            return Result.success(products);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 搜索产品
     */
    @Operation(summary = "搜索产品", description = "根据多个条件搜索产品")
    @PostMapping("/search")
    public Result<PageResult<ProductDTO>> searchProducts(@Valid @RequestBody ProductSearchDTO searchDTO) {
        try {
            PageResult<ProductDTO> products = productService.searchProducts(searchDTO);
            return Result.success(products);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 简单关键词搜索
     */
    @Operation(summary = "关键词搜索", description = "根据关键词搜索产品")
    @GetMapping("/search")
    public Result<PageResult<ProductDTO>> simpleSearch(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "12") Integer size,
            @RequestParam(defaultValue = "createdAt") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDirection) {
        try {
            ProductSearchDTO searchDTO = new ProductSearchDTO();
            searchDTO.setKeyword(keyword);
            searchDTO.setPage(page);
            searchDTO.setSize(size);
            searchDTO.setSortBy(sortBy);
            searchDTO.setSortDirection(sortDirection);
            
            PageResult<ProductDTO> products = productService.searchProducts(searchDTO);
            return Result.success(products);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取热门产品
     */
    @Operation(summary = "获取热门产品", description = "获取热门产品列表")
    @GetMapping("/hot")
    public Result<List<ProductDTO>> getHotProducts(
            @RequestParam(defaultValue = "8") Integer limit) {
        try {
            List<ProductDTO> products = productService.getHotProducts(limit);
            return Result.success(products);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取推荐产品
     */
    @Operation(summary = "获取推荐产品", description = "获取推荐产品列表")
    @GetMapping("/recommended")
    public Result<List<ProductDTO>> getRecommendedProducts(
            @RequestParam(defaultValue = "8") Integer limit) {
        try {
            List<ProductDTO> products = productService.getRecommendedProducts(limit);
            return Result.success(products);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 创建产品
     */
    @Operation(summary = "创建产品", description = "创建新产品")
    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public Result<ProductDTO> createProduct(@Valid @RequestBody ProductDTO productDTO) {
        try {
            ProductDTO createdProduct = productService.createProduct(productDTO);
            return Result.success("产品创建成功", createdProduct);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 更新产品
     */
    @Operation(summary = "更新产品", description = "更新产品信息")
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<ProductDTO> updateProduct(@PathVariable Long id, 
                                          @Valid @RequestBody ProductDTO productDTO) {
        try {
            ProductDTO updatedProduct = productService.updateProduct(id, productDTO);
            return Result.success("产品更新成功", updatedProduct);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 删除产品
     */
    @Operation(summary = "删除产品", description = "删除指定产品")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> deleteProduct(@PathVariable Long id) {
        try {
            productService.deleteProduct(id);
            return Result.success("产品删除成功", null);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取低库存产品（管理员）
     */
    @Operation(summary = "获取低库存产品", description = "获取库存低于阈值的产品")
    @GetMapping("/low-stock")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<List<ProductDTO>> getLowStockProducts(
            @RequestParam(defaultValue = "10") Integer threshold) {
        try {
            List<ProductDTO> products = productService.getLowStockProducts(threshold);
            return Result.success(products);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 更新产品库存
     */
    @Operation(summary = "更新产品库存", description = "更新指定产品的库存数量")
    @PutMapping("/{id}/stock")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> updateProductStock(@PathVariable Long id, 
                                         @RequestParam Integer quantity) {
        try {
            productService.updateProductStock(id, quantity);
            return Result.success("库存更新成功", null);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
}